import store from "@/store/index";
import { showErrorToast } from "@/util/message/index";
// 此vm参数为页面的实例，可以通过它引用vuex中的变量
export default (vm) => {
  // 初始化请求配置
  uni.$u.http.setConfig((config) => {
    /* config 为默认全局配置*/
    config.baseURL = process.env.VUE_APP_API_BASE_URL; /* 根域名 */
    return config;
  });
  uni.$u.http.interceptors.request.use((config) => {
    config.header["x-token"] = store.state.token ?? "";
    return config;
  });
  uni.$u.http.interceptors.response.use(
    async (response) => {
      if (response.data?.code === 20000) {
        return response.data;
      } else if (response.data?.code === 50008) {
        await uni.reLaunch({
          url: "/pages/index/index",
        });
        let error = new Error("存在多设备登陆，请重新登陆");
        showErrorToast(error);
        return Promise.reject(new Error("存在多设备登陆，请重新登陆"));
      } else if (response.data?.code === 20001) {
        await uni.reLaunch({
          url: "/pages/index/index",
        });
        let error = new Error(response.data?.message);
        showErrorToast(error);
        return Promise.reject(new Error(response.data?.message));
      } else if (!response.data?.code) {
        return;
      } else {
        await uni.reLaunch({
          url: "/pages/index/index",
        });
        let error = new Error("与服务器断开");
        showErrorToast(error);
        return Promise.reject(new Error("与服务器断开，请重新登陆"));
      }
    },
    async (response) => {
      await uni.reLaunch({
        url: "/pages/index/index",
      });
      let error = new Error("与服务器断开，请重新登陆");
      showErrorToast(error);
      return Promise.reject(new Error("与服务器断开，请重新登陆"));
    }
  );
};
